package com.genghis.rapidcrm.kernel;

import com.genghis.rapidcrm.kernel.model.RapidBaseModel;
import com.genghis.rapidcrm.kernel.module.RapidModuleModel;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component(RapidListViewModel.DEFAULT_LIST_VIEW_MODEL_BEAN_NAME)
public class RapidListViewModel extends RapidBaseModel {

    public static final String DEFAULT_LIST_VIEW_MODEL_BEAN_NAME = "rapidListViewModel";

    private final ApplicationContext applicationContext;

    private final RapidLinkModelProvider linkModelProvider;

    private RapidModuleModel moduleModel;

    public RapidListViewModel(ApplicationContext applicationContext,
                              RapidLinkModelProvider linkModelProvider) {

        this.applicationContext = applicationContext;
        this.linkModelProvider = linkModelProvider;
    }

    /**
     * Function to get the Quick Links for the List view of the module
     *
     * @param linkParams Map
     * @return <Array> List of Vtiger_Link_Model instances
     */
    public Map<String, List<RapidLinkModel>> getSideBarLinks(Map<String, Object> linkParams) {
        String[] linkTypes = new String[]{"SIDEBARLINK", "SIDEBARWIDGET"};
        Map<String, List<RapidLinkModel>> moduleLinks = this.getModule().getSideBarLinks(linkParams);

        String[] listLinkTypes = new String[]{"LISTVIEWSIDEBARLINK", "LISTVIEWSIDEBARWIDGET"};
        Map<String, List<RapidLinkModel>> listLinks =
                linkModelProvider.getAllByType(this.getModule().getId(), listLinkTypes);

        if (listLinks.get("LISTVIEWSIDEBARLINK") != null) {
            moduleLinks.computeIfAbsent("SIDEBARLINK", v -> new ArrayList<>())
                    .addAll(listLinks.get("LISTVIEWSIDEBARLINK"));
        }

        if (listLinks.get("LISTVIEWSIDEBARWIDGET") != null) {
            moduleLinks.computeIfAbsent("SIDEBARLINK", v -> new ArrayList<>())
                    .addAll(listLinks.get("LISTVIEWSIDEBARWIDGET"));
        }

        return moduleLinks;
    }

    public RapidModuleModel getModule() {
        if (this.moduleModel == null) {
            this.moduleModel = RapidModelBeanHelper.getModuleModelBean(RapidModuleModel.DEFAULT_MODULE_BEAN_NAME,
                    applicationContext);
        }
        return this.moduleModel;
    }

    public void setModule(RapidModuleModel module) {
        this.moduleModel = module;
    }

    public Map<String, List<RapidLinkModel>> getListViewMassActions(Map<String, Object> linkParams) {
        UsersPrivilegesModel currentUserModel = UsersPrivilegesModel.getCurrentUserPrivilegesModel();
        moduleModel = this.getModule();

        String[] linkTypes = {"LISTVIEWMASSACTION"};
        Map<String, List<RapidLinkModel>> links =
                this.linkModelProvider.getAllByType(moduleModel.getId(), linkTypes, linkParams);


        List<RapidLinkModel> massActionLinks = new ArrayList<>();
        if (currentUserModel.hasModuleActionPermission(moduleModel.getId(), "EditView")) {
            massActionLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEWMASSACTION")
                    .setLinkLabel("LBL_EDIT")
                    .setLinkUrl("javascript:Vtiger_List_Js.triggerMassEdit(\"" + moduleModel.getName() +
                            "?view=MassActionAjax&mode=showMassEditForm\");")
                    .setLinkIcon(""));
        }

        if (currentUserModel.hasModuleActionPermission(moduleModel.getId(), "Delete")) {
            massActionLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEWMASSACTION")
                    .setLinkLabel("LBL_DELETE")
                    .setLinkUrl("javascript:Vtiger_List_Js.massDeleteRecords(\"" + moduleModel.getName() +
                            "?action=MassDelete\");")
                    .setLinkIcon(""));
        }

        RapidModuleModel modCommentsModel = RapidModelBeanHelper.getModuleModelBean("ModComments",
                applicationContext);
        if (moduleModel.isCommentEnabled() && modCommentsModel.isPermitted("EditView")) {
            massActionLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEWMASSACTION")
                    .setLinkLabel("LBL_ADD_COMMENT")
                    .setLinkUrl(moduleModel.getName() + "?view=MassActionAjax&mode=showAddCommentForm")
                    .setLinkIcon(""));
        }

        links.computeIfAbsent("LISTVIEWMASSACTION", v -> new ArrayList<>()).addAll(massActionLinks);
        return links;
    }

    public Map<String, ?> getListViewHeaders() {
        return new HashMap<>(0);
    }

    public Integer getListViewCount() {
        return 0;
    }

    public List<?> getListViewEntries(RapidPagingModel pagingModel) {
        return new ArrayList<>(0);
    }

    /**
     * Function to get Setting links
     *
     * @return array of setting links
     */
    public List<RapidLinkModel> getSettingLinks() {
        return this.getModule().getSettingLinks();
    }

    /**
     * Function to get Basic links
     *
     * @return array of Basic links
     */
    public List<RapidLinkModel> getBasicLinks() {
        List<RapidLinkModel> basicLinks = new ArrayList<>();
        RapidModuleModel moduleModel = this.getModule();
        boolean createPermission = UsersPrivilegesModel.isPermitted(moduleModel.getName(), "EditView");
        if (createPermission) {
            basicLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEWBASIC")
                    .setLinkLabel("LBL_ADD_RECORD")
                    .setLinkUrl(moduleModel.getCreateRecordUrl())
                    .setLinkIcon(""));
        }
        return basicLinks;
    }

    /*
     * Function to give advance links of a module
     *	@RETURN array of advanced links
     */
    public List<RapidLinkModel> getAdvancedLinks() {
        RapidModuleModel moduleModel = this.getModule();
        boolean createPermission = UsersPrivilegesModel.isPermitted(moduleModel.getName(), "EditView");
        List<RapidLinkModel> advancedLinks = new ArrayList<>();
        boolean importPermission = UsersPrivilegesModel.isPermitted(moduleModel.getName(), "Import");
        if (importPermission && createPermission) {
            advancedLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEW")
                    .setLinkLabel("LBL_IMPORT")
                    .setLinkUrl(moduleModel.getImportUrl())
                    .setLinkIcon(""));
        }

        boolean exportPermission = UsersPrivilegesModel.isPermitted(moduleModel.getName(), "Export");
        if (exportPermission) {
            advancedLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEW")
                    .setLinkLabel("LBL_EXPORT")
                    .setLinkUrl("javascript:Vtiger_List_Js.triggerExportAction(\"" + this.getModule().getExportUrl() + "\")")
                    .setLinkIcon(""));
        }

        boolean duplicatePermission = UsersPrivilegesModel.isPermitted(moduleModel.getName(), "DuplicatesHandling");
        if (duplicatePermission) {
            advancedLinks.add(new RapidLinkModel()
                    .setLinkType("LISTVIEWMASSACTION")
                    .setLinkLabel("LBL_FIND_DUPLICATES")
                    .setLinkUrl("Javascript:Vtiger_List_Js.showDuplicateSearchForm(\"index.php?module=" + moduleModel.getName() +
                            "&view=MassActionAjax&mode=showDuplicatesSearchForm\")")
                    .setLinkIcon(""));
        }

        return advancedLinks;
    }

    /**
     * Function to get the list of listview links for the module
     *
     * @param linkParams <Array>
     * @return <Array> - Associate array of Link Type to List of Vtiger_Link_Model instances
     */
    public Map<String, List<RapidLinkModel>> getListViewLinks(Map<String, Object> linkParams, UsersRecordModel currentUserModel) {
        RapidModuleModel moduleModel = this.getModule();

        String[] linkTypes = new String[]{"LISTVIEWBASIC", "LISTVIEW", "LISTVIEWSETTING"};
        Map<String, List<RapidLinkModel>> links = linkModelProvider.getAllByType(moduleModel.getId(), linkTypes, linkParams);

        List<RapidLinkModel> basicLinks = this.getBasicLinks();
        links.computeIfAbsent("LISTVIEWBASIC", v -> new ArrayList<>()).addAll(basicLinks);

        List<RapidLinkModel> advancedLinks = this.getAdvancedLinks();
        links.computeIfAbsent("LISTVIEW", v -> new ArrayList<>()).addAll(advancedLinks);

        if (currentUserModel.isAdminUser()) {
            List<RapidLinkModel> settingsLinks = this.getSettingLinks();
            links.computeIfAbsent("LISTVIEWSETTING", v -> new ArrayList<>()).addAll(settingsLinks);
        }

        return links;
    }
}
